package art.client.activites;

import java.util.List;

import art.client.ClientFactory;
import art.client.ClientUtils;
import art.client.views.ArtUploadView;
import art.shared.entities.GenreShared;
import art.shared.entities.LoginInfo;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;

public class ArtUploadActivity extends AbstractActivity {

	private ClientFactory clientFactory = null;
	private LoginInfo loginInfo = null;

	public ArtUploadActivity(ClientFactory clientFactory, LoginInfo loginInfo) {
		this.clientFactory = clientFactory;
		this.loginInfo = loginInfo;
	}

	@Override
	public void start(AcceptsOneWidget containerWidget, EventBus eventBus) {
		initView(containerWidget);
		
	}

	private void initView(final AcceptsOneWidget containerWidget) {
		if (loginInfo == null) {
			ClientUtils.getUserService().getLoginInfo(
					new AsyncCallback<LoginInfo>() {

						@Override
						public void onSuccess(LoginInfo loginInfo) {
							executeInit(containerWidget);
						}

						@Override
						public void onFailure(Throwable arg0) {

						}
					});
		} else {
			executeInit(containerWidget);
		}
	}

	private void executeInit(final AcceptsOneWidget containerWidget) {
		setGenres(containerWidget, loginInfo);
	}

	private void setGenres(final AcceptsOneWidget containerWidget,
			final LoginInfo loginInfo) {
		ClientUtils.getArtService().getGenres(
				new AsyncCallback<List<GenreShared>>() {

					@Override
					public void onFailure(Throwable arg0) {
					}

					@Override
					public void onSuccess(List<GenreShared> genres) {
						ArtUploadView artUploadView = clientFactory
								.getArtUploadView(loginInfo, genres);
						containerWidget.setWidget(artUploadView.asWidget());
						setFormSubmitAction(artUploadView);
					}
				});
	}

	private void setFormSubmitAction(final ArtUploadView artUploadView) {
		artUploadView.getUploadButton().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent arg0) {
				if (artUploadView.getTitleField().getValue().isEmpty()
						|| !(artUploadView.getFileUpload().getFilename().isEmpty()
							^ artUploadView.getArtField().getValue().isEmpty())){
					return;
				}
				artUploadView.getForm().submit();
			}
		});
		artUploadView.getForm().addSubmitCompleteHandler(
				new SubmitCompleteHandler() {

					@Override
					public void onSubmitComplete(SubmitCompleteEvent event) {
						artUploadView.clearForm();
					}
				});
	}

}
